/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pe.gov.mtc.dgac.licencias.action;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;
import pe.gov.mtc.dgac.licencias.bean.LicenciaTO;
import pe.gov.mtc.dgac.licencias.bean.PaisTO;
import pe.gov.mtc.dgac.licencias.bean.UbigeoTO;
import pe.gov.mtc.dgac.licencias.bean.Usuario;
import pe.gov.mtc.dgac.licencias.exception.BusinessException;
import pe.gov.mtc.dgac.licencias.form.LoginForm;
import pe.gov.mtc.dgac.licencias.service.ClientelicenciaService;
import pe.gov.mtc.dgac.licencias.service.UbigeoService;
import pe.gov.mtc.dgac.licencias.service.UsuarioService;
import pe.gov.mtc.dgac.licencias.struts.Constants;

/**
 *
 * @author externo.gamaro
 */
public class UsuarioAction extends DispatchAction {
    
    /* forward name="success" path="" */
    private final static String SUCCESS = "success";
    private Log logger = LogFactory.getLog(this.getClass());
    private UsuarioService usrService;
    private UbigeoService ubigService;
    private ClientelicenciaService clilicService;
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    /*public ActionForward execute(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        logger.debug("execute");
        return mapping.findForward(SUCCESS);
        
    }*/
    public UsuarioAction(UsuarioService usrService,UbigeoService ubigService,ClientelicenciaService clilicService) {
        super();
        this.usrService = usrService;
        this.ubigService= ubigService;
        this.clilicService=clilicService;
    }
    
    public ActionForward validarUsuario(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("validarUsuario");
        
        if(isValidUser(request,form)) {
          logger.debug("verdadero");
          // Inicialisar variables generales
           HttpSession sesion = request.getSession();
           List<UbigeoTO> listaubigeo=ubigService.listUbigeo(0L);
           List<PaisTO> listapaises=ubigService.listPaises("");
           List<LicenciaTO> listlicencias=clilicService.listarLicencias();
           sesion.setAttribute("ubigeo", listaubigeo);
           sesion.setAttribute("paises", listapaises); 
           sesion.setAttribute("listLicencias",listlicencias); 
          return mapping.findForward(Constants.SUCCESS.getValue());
        }else{
          logger.debug("falso");
          return mapping.findForward(Constants.LOGIN.getValue());
        }
    }
    
    private boolean isValidUser(HttpServletRequest req,ActionForm form) {
        logger.debug("isValidUser");
        LoginForm loginfrm=(LoginForm) form;
        boolean result=false;
        ActionMessages errors = new ActionMessages();        
      
      try{
        
        List<Usuario> list=usrService.buscarUsuario(loginfrm.getLogin());
      
        if(list.size()>0){
        
           Usuario usr=list.get(0);
           if(usr.getPassword().equals(loginfrm.getPassword())) { 
               result=true;
               req.getSession().setAttribute("usr",usr);
           }else{
              errors.add("password", new ActionMessage("errors.password",loginfrm.getPassword()));  
           }
        }else{
          errors.add("login", new ActionMessage("errors.login", loginfrm.getLogin()));  
        }   
        
        
      }catch(Exception e){
        logger.debug(e);  
        errors.add("login", new ActionMessage("errors.interno","validarUsuario"));  
      }
      
       if (!errors.isEmpty()) saveErrors(req, errors);
       return result;
    }
    
    public ActionForward cerrarSesion(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("cerrarSesion");
        request.getSession().invalidate();
        return mapping.findForward(Constants.LOGIN.getValue());
    }
}